<!--
  * 工时功能
  *
  * @Author:    yjg
  * @Date:      2024-09-09 11:02:13
  * @Copyright  v1.0
-->
<template>
  <a-modal :title="form.workingHoursId ? '编辑' : '添加'" :width="600"  :open="visibleFlag"  @cancel="onClose" :maskClosable="false" :destroyOnClose="true">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" >
		<a-form-item label="加班日期" name="overtimeData">
		  <a-date-picker valueFormat="YYYY-MM-DD" v-model:value="form.overtimeData" style="width: 100%" placeholder="加班日期" @change="handleOvertimeData" />
		</a-form-item>
		<a-form-item label="部门" name="departmentIds">
		  <DepartmentTreeSelect ref="departmentTreeSelect" width="100%" :init="false" :disabled="form.workingHoursId != null || form.overtimeData == null" v-model:value="form.departmentIds" @change="handleDepartment"/>
		</a-form-item>
		<a-form-item label="人员选择" name="memberIdList">
		  <a-select mode="multiple" v-model:value="form.memberIdList" optionFilterProp="title" :disabled="form.workingHoursId != null" placeholder="请人员选择">
			<a-select-option v-for="item in memberList" :key="item.employeeId" :title="item.loginName">{{ item.loginName }},{{item.actualName}}</a-select-option>
		  </a-select>
		</a-form-item>
		<a-form-item label="班别类型"  name="banbieType">
		  <DictSelect style="width: 100%" key-code="BANBIE_TYPE" v-model:value="form.banbieType" @change="handleChange()"/>
		</a-form-item>
		<a-form-item label="加班类型"  name="overtimeResult">
		  <DictSelect key-code="OVERTIM_TYPE" v-model:value="form.overtimeType" @change="handleChange()"/>
		</a-form-item>
		
		<a-form-item label="建议加班1" name="noonOverTime">
		  <a-time-range-picker  v-model:value="noonOverTime" @change="onNoonRangeChange"  format="HH:mm" :minute-step="30" :second-step="60" />
		  <div style="font-weight: bold;color: red;">录中午连班（大夜班时录23:30-24:00）</div>
		</a-form-item>
		<a-form-item label="建议加班2" name="nightOverTime">
		 <a-time-range-picker v-model:value="nightOverTime" @change="onNightRangeChange" format="HH:mm" :minute-step="30" :second-step="60" />
         <div style="font-weight: bold;color: red;">录晚上连班（大夜班时录05:00-06:00）</div>
		</a-form-item>
		<a-form-item label="建议加班3" name="nightShiftOverTime">
          <a-time-picker v-model:value="nightshiftStartOvertime" @change="shiftStartTime" format="HH:mm" :minute-step="30"/>
          至
		  <a-time-picker v-model:value="nightshiftEndOvertime" @change="shiftEndTime"  format="HH:mm"  :minute-step="30"/>
          <div style="font-weight: bold;color: red;">录周日加班</div>
		</a-form-item>
		<a-form-item label="加班数2"  name="overtimeNumber">
		  <a-input-number  style="width: 100%"  v-model:value="form.overtimeNumber2" placeholder="加班数2" />
		</a-form-item>
		 <a-form-item label="加班原因"  name="overtimeResult">
		   <a-textarea
		     :auto-size="{ minRows: 2, maxRows: 4 }"
		     v-model:value="form.overtimeResult"
		     placeholder="请输入加班原因"
		     :maxlength="250"
		     :showCount="true"
		   />
		 </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit(false)">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script lang="ts" setup>
  import { reactive, ref, nextTick } from 'vue';
  import dayjs, { Dayjs } from 'dayjs';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { workingHoursApi } from '/@/api/business/working-hours/working-hours-api';
  import { employeeApi } from '/@/api/system/employee-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import DictSelect from '/@/components/support/dict-select/index.vue';
  import { Solar } from 'lunar-javascript';
  import DepartmentTreeSelect from '/src/components/system/department-tree-select/multiple-choice.vue';
  
  const memberList = ref([]); //人员列表
  let solar = Solar.fromDate(new Date());
  const weeks = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
  const overtimeData = ref(null);
 
 // const noonOverTime = ref<[Dayjs, Dayjs]>([ dayjs('12:00', "HH:mm"),  dayjs('12:30', "HH:mm")]);       // 时间参数1
  const noonOverTime = ref<[Dayjs, Dayjs]>([null,null]);       // 时间参数1
  const nightOverTime = ref<[Dayjs, Dayjs]>([null,null]);      // 时间参数2
  const nightshiftStartOvertime = ref(null);
  const nightshiftEndOvertime = ref(null);
  

     
    // ------------------------ 时间范围 ------------------------
      const onNoonRangeChange = (value: [Dayjs, Dayjs], dateString: [string, string]) => {
   	    form.noonStartOvertime = dateString[0]
   	    form.noonEndOvertime = dateString[1]
      };
      
      const onNightRangeChange = (value: [Dayjs, Dayjs], dateString: [string, string]) => {
     	form.nightStartOvertime = dateString[0]
     	form.nightEndOvertime = dateString[1]
      };
	  
	  const shiftStartTime = (value,dateString)=>{
		  form.nightshiftStartOvertime = dateString;
	  }
	  const shiftEndTime = (value,dateString)=>{
	  	  form.nightshiftEndOvertime = dateString;
	  }
	  //-------------------------选择加班时间----------------------------
	  const handleOvertimeData = ()=>{
		  form.departmentIds = [];
	  }
	
	  //---------------------------选择部门-------------------------------
	  const departmentTreeSelect = ref();
	  async function handleDepartment(){
	  	  try{
			  memberList.value = null;
			  if(form.departmentIds ==null || form.departmentIds.length === 0){
				return;
			  }  
	  		  let queryResult = await employeeApi.selectEmployeeByDeptIds(form.departmentIds,form.overtimeData,0)
			  memberList.value = queryResult.data
	  	  }catch(e){
	  		  smartSentry.captureError(e);
	  	  } finally {
	          
	      }
	  }
	
	//---------------------------------班别及加班类型处置------------------------------------
	const handleChange = ()=>{
		noonOverTime.value =  [null, null];     
		form.noonStartOvertime = null
		form.noonEndOvertime = null
		nightOverTime.value = [null,null];    
		form.nightStartOvertime = null
		form.nightEndOvertime = null
		form.nightshiftStartOvertime = null
		form.nightshiftEndOvertime = null
		nightshiftStartOvertime.value = null
		nightshiftEndOvertime.value = null
		form.overtimeNumber2 = null
		if(form.banbieType == 'ZAOBAN' && form.overtimeType == 'DAILY_OVERTIME'){
			noonOverTime.value =  [ dayjs('12:00', "HH:mm"),  dayjs('12:30', "HH:mm")];       // 时间参数1
			form.noonStartOvertime = '12:00'
			form.noonEndOvertime = '12:30'
			nightOverTime.value = [ dayjs('17:00', "HH:mm"),  dayjs('17:30', "HH:mm")];      // 时间参数2
			form.nightStartOvertime = '17:00'
			form.nightEndOvertime = '17:30'
			form.overtimeNumber2 = 1
		}else if (form.banbieType == 'BAIBAN' && form.overtimeType == 'WEEKEND_OVERTIME'){
			noonOverTime.value =  [ dayjs('12:00', "HH:mm"),  dayjs('12:30', "HH:mm")];       // 时间参数1
			form.noonStartOvertime = '12:00'
			form.noonEndOvertime = '12:30'
			nightOverTime.value = [ dayjs('17:00', "HH:mm"),  dayjs('17:30', "HH:mm")];      // 时间参数2
			form.nightStartOvertime = '17:00'
			form.nightEndOvertime = '17:30'
			nightshiftStartOvertime.value = dayjs('08:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('20:00', 'HH:mm'); 
			form.nightshiftStartOvertime = '08:00'
			form.nightshiftEndOvertime = '20:00'
			form.overtimeNumber2 = 10
		}else if (form.banbieType == 'BAIBAN' && form.overtimeType == 'HOLIDAY_OVERTIME'){
			noonOverTime.value =  [ dayjs('11:30', "HH:mm"),  dayjs('12:00', "HH:mm")];       // 时间参数1
			form.noonStartOvertime = '11:30'
			form.noonEndOvertime = '12:00'
			nightOverTime.value = [ dayjs('17:30', "HH:mm"),  dayjs('18:00', "HH:mm")];      // 时间参数2
			form.nightStartOvertime = '17:30'
			form.nightEndOvertime = '18:00'
			nightshiftStartOvertime.value = dayjs('08:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('20:00', 'HH:mm'); 
			form.nightshiftStartOvertime = '08:00'
			form.nightshiftEndOvertime = '20:00'
			form.overtimeNumber2 = 10
		}else if (form.banbieType == 'DAYEBAN' && form.overtimeType == 'DAILY_OVERTIME'){
			noonOverTime.value =  [ dayjs('23:30', "HH:mm"),  dayjs('24:00', "HH:mm")];       // 时间参数1
			form.noonStartOvertime = '23:30'
			form.noonEndOvertime = '24:00'
			nightOverTime.value = [ dayjs('05:30', "HH:mm"),  dayjs('06:00', "HH:mm")];      // 时间参数2
			form.nightStartOvertime = '05:30'
			form.nightEndOvertime = '06:00'
			nightshiftStartOvertime.value = dayjs('00:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('00:00', 'HH:mm'); 
			form.nightshiftStartOvertime = '00:00'
			form.nightshiftEndOvertime = '00:00'
			form.overtimeNumber2 = 1
		}else if (form.banbieType == 'DAYEBAN' && form.overtimeType == 'WEEKEND_OVERTIME'){
			noonOverTime.value =  [ dayjs('23:30', "HH:mm"),  dayjs('24:00', "HH:mm")];       // 时间参数1
			form.noonStartOvertime = '23:30'
			form.noonEndOvertime = '24:00'
			nightOverTime.value = [ dayjs('05:30', "HH:mm"),  dayjs('06:00', "HH:mm")];      // 时间参数2
			form.nightStartOvertime = '05:30'
			form.nightEndOvertime = '06:00'
			nightshiftStartOvertime.value = dayjs('20:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('08:00', 'HH:mm'); 
			form.nightshiftStartOvertime = '20:00'
			form.nightshiftEndOvertime = '08:00'
			form.overtimeNumber2 = 10
		}else if (form.banbieType == 'DAYEBAN' && form.overtimeType == 'HOLIDAY_OVERTIME'){
			noonOverTime.value =  [ dayjs('23:30', "HH:mm"),  dayjs('24:00', "HH:mm")];       // 时间参数1
			form.noonStartOvertime = '23:30'
			form.noonEndOvertime = '24:00'
			nightOverTime.value = [ dayjs('05:30', "HH:mm"),  dayjs('06:00', "HH:mm")];      // 时间参数2
			form.nightStartOvertime = '05:30'
			form.nightEndOvertime = '06:00'
			nightshiftStartOvertime.value = dayjs('20:00', 'HH:mm');
			nightshiftEndOvertime.value =  dayjs('08:00', 'HH:mm'); 
			form.nightshiftStartOvertime = '20:00'
			form.nightshiftEndOvertime = '08:00'
			form.overtimeNumber2 = 10
		}
	}
	
	   function handleBanbieType(){
		   if(form.banbieType == 'ZAOBAN'){
			   form.overtimeType = 'DAILY_OVERTIME'
			   noonOverTime.value =  [ dayjs('12:00', "HH:mm"),  dayjs('12:30', "HH:mm")];       // 时间参数1
			   form.noonStartOvertime = '12:00'
			   form.noonEndOvertime = '12:30'
			   nightOverTime.value = [ dayjs('17:00', "HH:mm"),  dayjs('17:30', "HH:mm")];      // 时间参数2
			   form.nightStartOvertime = '17:00'
			   form.nightEndOvertime = '17:30'
			   form.overtimeNumber2 = 1
		   }else if(form.banbieType == 'BAIBAN'){
			   form.overtimeType = 'WEEKEND_OVERTIME'
			   noonOverTime.value =  [ dayjs('12:00', "HH:mm"),  dayjs('12:30', "HH:mm")];       // 时间参数1
			   form.noonStartOvertime = '12:00'
			   form.noonEndOvertime = '12:30'
			   nightOverTime.value = [ dayjs('17:00', "HH:mm"),  dayjs('17:30', "HH:mm")];      // 时间参数2
			   form.nightStartOvertime = '17:00'
			   form.nightEndOvertime = '17:30'
			   form.overtimeNumber2 = 10
			   nightshiftStartOvertime.value = dayjs('18:00', 'HH:mm'); 
			   nightshiftEndOvertime.value =  dayjs('20:00', 'HH:mm'); 
			   form.nightshiftStartOvertime = '18:00'
			   form.nightshiftEndOvertime = '20:00'
		   }else if(form.banbieType == 'DAYEBAN'){
			   form.overtimeType = null
			   noonOverTime.value =  [ dayjs('23:30', "HH:mm"),  dayjs('23:59', "HH:mm")];       // 时间参数1
			   form.noonStartOvertime = '23:30'
			   form.noonEndOvertime = '24:00'
			   nightOverTime.value = [ dayjs('5:30', "HH:mm"),  dayjs('06:00', "HH:mm")];      // 时间参数2
			   form.nightStartOvertime = '5:30'
			   form.nightEndOvertime = '06:00'
			   nightshiftStartOvertime.value = dayjs('20:00', 'HH:mm'); 
			   nightshiftEndOvertime.value = dayjs('08:00', 'HH:mm'); 
			   form.nightshiftStartOvertime = '20:00'
			   form.nightshiftEndOvertime = '08:00'
			   form.overtimeNumber2 = 1
		   }else{
			   form.overtimeType = null
			   noonOverTime.value =  [null, null];       // 时间参数1
			   form.noonStartOvertime = null
			   form.noonEndOvertime = null
			   nightOverTime.value = [null,null];      // 时间参数2
			   form.nightStartOvertime = null
			   form.nightEndOvertime = null
			   nightshiftStartOvertime.value = null
			   nightshiftEndOvertime.value = null
			   form.overtimeNumber2 = null
		   }
	   }

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);
  

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }

	form.overtimeNumber = 1
	if(form.workingHoursId != null){
		if(!_.isEmpty(form.noonStartOvertime) && !_.isEmpty(form.noonEndOvertime)){
			noonOverTime.value = [ dayjs(form.noonStartOvertime, "HH:mm"),  dayjs(form.noonEndOvertime, "HH:mm")];
		}
		if(!_.isEmpty(form.nightStartOvertime) && !_.isEmpty(form.nightEndOvertime)){
			nightOverTime.value = [ dayjs(form.nightStartOvertime, "HH:mm"),  dayjs(form.nightEndOvertime, "HH:mm")];
		}
		if(!_.isEmpty(form.nightshiftStartOvertime) && !_.isEmpty(form.nightshiftEndOvertime)){
			nightshiftStartOvertime.value =dayjs(form.nightshiftStartOvertime, "HH:mm")
			nightshiftEndOvertime.value = dayjs(form.nightshiftEndOvertime, "HH:mm");
		}else{
			nightshiftStartOvertime.value = null;
			nightshiftEndOvertime.value = null;
		}
	}else{
	   form.overtimeData = overtimeData.value
	}
	
	if (form.overtimeType && form.overtimeType.length > 0) {
	  form.overtimeType = form.overtimeType[0].valueCode;
	}
	if (form.banbieType && form.banbieType.length > 0) {
	  form.banbieType = form.banbieType[0].valueCode;
	}
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }
  
  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
	  //工时ID
	  workingHoursId: undefined, 
	  //部门ID
	  departmentIds: undefined,
	  //部门名称
	  deptName: undefined, 
	  //姓名
	  name: undefined,
	  //工作号
	  jobNumber: undefined,
	  //班别类型
	  banbieType: undefined,
	  //就餐数
	  mealsNumber: undefined,
	  //加班日期
	  overtimeData : undefined,
	  //加班数
	  overtimeNumber: undefined,
	  //加班数2
	  overtimeNumber2: undefined,
	  //加班类型
	  overtimeType: undefined,
	  //建议加班开始时间1
	  noonStartOvertime: undefined,
	  //建议加班结束时间1
	  noonEndOvertime: undefined,
	  //建议加班开始时间2
	  nightStartOvertime: undefined,
	  //建议加班结束时间2
	  nightEndOvertime: undefined,
	  //建议加班开始时间3
	  nightshiftStartOvertime: undefined,
	  //建议加班结束时间3
	  nightshiftEndOvertime : undefined,
	  //加班原因
	  overtimeResult: undefined,
	  //人员信息
	  memberIdList: undefined,
	  //工时类型（0工时，1加班）
	  overtimeFlag: 0,
	  
  };
  
  let form = reactive(_.cloneDeep(formDefault));
  function reset() {
    Object.assign(form, formDefault);
    formRef.value.resetFields();
  }

  const rules = {
        departmentId: [{ required: true, message: '请选择部门' }],
		overtimeData: [{ required: true, message: '加班日期' }],
		memberIdList: [{ required: true, message: '请选择人员' }],
		banbieType: [{ required: true, message: '班别类型不能为空' }],
		overtimeType: [{ required: true, message: '加班类型不能为空' }],
  };

  // 点击确定，验证表单
  async function onSubmit(keepAdding) {
    try {

      await formRef.value.validateFields();
	  let week = '星期'+Solar.fromDate(new Date(form.overtimeData)).getWeekInChinese();
	  const stringInArray = weeks.includes(week);
	  if(form.nightshiftStartOvertime != null && form.nightshiftEndOvertime != null){
		  let startStatus = form.nightshiftStartOvertime.localeCompare("08:00");
		  let endStatus = form.nightshiftEndOvertime.localeCompare("20:00");
		  if(stringInArray){ //判断是否周一到周六，ture(是)
			  if(startStatus == 0 && endStatus == 0){ //判断区间是否在【08:00-20:00】之间
				  message.error('周一到周六【08:00-20:00】区间内除连班以外的工时请在【加班录入】中输入!');
				  return
			  } 
		  }
	  }
	  save(keepAdding);
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save(keepAdding) {
    SmartLoading.show();
    try {
      if (form.workingHoursId) {
        await workingHoursApi.update(form);
      } else {
		workingHoursApi.queryByNumberAndDate(form.jobNumber,form.overtimeData); //验证工号和日期
        await workingHoursApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
	  if (keepAdding) {
	    reset();
	  } else {
	    onClose();
	  }
     
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  defineExpose({
    show,
  });
</script>
